/**
 * 解析时间并指定格式
 * @param {Object} time
 * @param {Object} cFormat
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (('' + time).length === 10) time = parseInt(time) * 1000
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') return ['日', '一', '二', '三', '四', '五', '六'][value]
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

export function parseStrToDate(Str) {
    var date = Str;
    date = date.substring(0, 19);
    date = date.replace(/-/g, '/');
    var timestamp = new Date(date).getTime();
    return timestamp
}

export function getDateDiff(time1Str) {
    const time1 = parseStrToDate(time1Str)

    const time2 = new Date().getTime()
    var times = time1 - time2//时间差的毫秒数

    var days = parseInt(times / (24 * 1000 * 3600));//计算相差的天数
    var leave = times % (24 * 3600 * 1000);//计算天数后剩余的毫秒数

    var h = parseInt(leave / (3600 * 1000));//计算小时数

    //计算分钟数
    var h_leave = leave % (3600 * 1000);
    var min = parseInt(h_leave / (60 * 1000));

    //计算秒数
    var min_leave = h_leave % (60 * 1000);
    var sec = parseInt(min_leave / 1000);
    return `${days}天${h}小时${min}分钟${sec}秒`
}
